package com.wangjiang.mario.admin.system.domain.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wangjiang.mario.admin.common.util.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;


/**
 * 微信小程序的工具类
 */
public class WxAppUtil {
    // 获取openid的链接
    public static final String CODE2_SESSION_URL_STRING = "https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code";

    // 获取access_token
    public static final String ACCESS_TOKEN_URL_STRING = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}";

    // 获取图片地址
    public static final String CREATE_QRCODE_URL_STRING = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token={}";
    public static final String GET_QRCODE_URL_STRING = "https://api.weixin.qq.com/wxa/getwxacode?access_token={}";
    public static final String GET_UNLIMITED_QRCODE_URL_STRING = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={}";


    public static final String SESSION_KEY = "session_key";

    // 获取完整获取openid的接口url
    public static String getCode2SessionURLString(String appid, String appsecret, String code) {
        return StringUtils.format(CODE2_SESSION_URL_STRING, appid, appsecret, code);
    }

    // 获取access_token接口返回
    public static String getAccessToken(String appid, String appSecret) {
        String realURLString = StringUtils.format(ACCESS_TOKEN_URL_STRING, appid, appSecret);
        return HttpUtil.get(realURLString);
    }

    public static String getSessionKey (String appid, String appsecret, String code) {
        JSONObject jsonObject = JSONObject.parseObject(HttpUtil.get(getCode2SessionURLString(appid, appsecret, code)));
        if(jsonObject.containsKey(SESSION_KEY)) {
            return (String) jsonObject.get(SESSION_KEY);
        }
        return null;
    }

    /**
     * 创建二维码
     * @param accessToken
     */
    public static InputStream  createQRCode(String accessToken, String path, String width) throws IOException {
        Map<String, Object> params = new HashMap<>();
        params.put("path", path);
        params.put("width", width);
        return getInputStreamFromUrl(CREATE_QRCODE_URL_STRING, params, accessToken);
    }

    public static InputStream getQRCode(String accessToken, String path, String width) throws IOException {
        Map<String, Object> params = new HashMap<>();
        params.put("path", path);
        params.put("width", width);

        return getInputStreamFromUrl(GET_QRCODE_URL_STRING, params, accessToken);
    }

    public static InputStream getUnlimitedQRCode(String accessToken, String path, String width, String scene) throws IOException {
        Map<String, Object> params = new HashMap<>();
        params.put("path", path);
        params.put("width", width);
        params.put("scene", scene);

        return getInputStreamFromUrl(GET_UNLIMITED_QRCODE_URL_STRING, params, accessToken);

    }

    private static InputStream getInputStreamFromUrl(String not_parsed_url, Map params, String accessToken) throws IOException  {
        String url = StringUtils.format(not_parsed_url, accessToken);

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost httpPost = new HttpPost(url);  // 接口
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        String body = JSON.toJSONString(params);           //必须是json模式的 post
        StringEntity entity;
        entity = new StringEntity(body);
        entity.setContentType("image/png");

        httpPost.setEntity(entity);
        HttpResponse response;

        response = httpClient.execute(httpPost);
        InputStream inputStream = response.getEntity().getContent();
        return inputStream;
    }


}
